package cn.ccimage.passwordkeeper;

import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.widget.TextViewCompat;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Set;

public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {
    public static final String PREFS_NAME = "SimpleDataStorage";
    private SharedPreferences sharedPref;

    private String keyprefCurrentPwd;
    private String keyprefCurrentTime;
    private String keyprefHistoryPwd;
    private String keyprefHistoryTime;
    private String keyprefGlobalPwd;
    private String keyprefGlobalPwdCheck;
    private String keyprefPasswordLength;
    private String keyprefEnableFingerprint;
    private String kStringBlank = "";

    private static final int REQUEST_CODE = 10001;
    private static final int SETTING_CODE = 10002;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);


        /* <--- 开始设置界面 */
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        final SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
        final String key = getString(R.string.preference_key_pwd_length);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                final View theview = view;

                DialogInterface.OnClickListener confirmCallback = new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                    try {
                        int pwdLen = Integer.parseInt(sp.getString(key, "8"));
                        String code = PasswordLogic.generateCode(pwdLen);
                        SaveCurrentPassword(code);

                        Snackbar.make(theview, R.string.info_text_newpassword, Snackbar.LENGTH_LONG)
                                .setAction("Action", null).show();
                    }
                    catch (Exception ex){
                        Snackbar.make(theview, R.string.info_text_exception, Snackbar.LENGTH_LONG)
                                .setAction("Action", null).show();
                    }
                    }
                };

                DialogInterface.OnClickListener cancelCallback = new DialogInterface.OnClickListener(){
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // DO Nothing;
                    }
                };
                String title = getString(R.string.info_text_createpwd_title);
                String body = getString(R.string.info_text_createpwd_body);
                confirmSomething(title, body,confirmCallback, cancelCallback);
            }
        });

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);
        /* 设置界面结束--> */
        GetPreferenceKey();

        ReadCurrentPassword();

        ListView historyView = (ListView)findViewById(R.id.listview_historydata);

        final ArrayList<HistoryData> list = new ArrayList<HistoryData>();
        MakeHistoryData(list);
        HistoryAdapter adapter = new HistoryAdapter(this, mHandle, list);
        historyView.setAdapter(adapter);
        historyView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Log.v("History-click", list.get(position).datetime);
            }
        });

        if(CheckUserPassword()) {
            //显示登录框
            Intent intent = new Intent(this, LoginActivity.class);
            startActivityForResult(intent, REQUEST_CODE);
        }
        else{
            Toast.makeText(this, R.string.info_text_first_use, Toast.LENGTH_LONG).show();
            //显示设置
            Intent intent = new Intent(this, SettingsActivity.class);
            startActivityForResult(intent, SETTING_CODE);
        }
    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            Intent intent = new Intent(this, SettingsActivity.class);
            startActivity(intent);
            return true;
        }
        else if(id == R.id.action_help) {
            Intent intent = new Intent(this, HelpActivity.class);
            startActivity(intent);
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        if (id == R.id.nav_current) {
            ReadCurrentPassword();
        } else if (id == R.id.nav_history) {
            ReadHistoryPassword();
        } else if (id == R.id.nav_setting) {
            Intent intent = new Intent(this, SettingsActivity.class);
            startActivity(intent);
        }
        else if (id == R.id.nav_help) {
            Intent intent = new Intent(this, HelpActivity.class);
            startActivity(intent);
        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }


    private void SaveCurrentPassword(String code) {
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dt = df.format(new Date());

        SharedPreferences.Editor editor = sharedPref.edit();
        editor.putString(keyprefCurrentPwd, code);
        editor.putString(keyprefCurrentTime, dt);
        editor.commit();
        ShowCurrentpwd(code, dt);

        AddHistoryData(code,dt);
    }

    private void ReadCurrentPassword() {
        String code = sharedPref.getString(keyprefCurrentPwd, kStringBlank);
        String dt = sharedPref.getString(keyprefCurrentTime, kStringBlank);

        ShowCurrentpwd(code, dt);
    }
    private void ShowCurrentpwd(String code, String dt) {
        TextView txt = (TextView)findViewById(R.id.main_text_label);
        txt.setText(code);
        TextView datetime = (TextView)findViewById(R.id.main_datetime_label);
        datetime.setText(dt);

        displayCurrentPassword(true);
    }
    private void confirmSomething(String title, String message, DialogInterface.OnClickListener confirm, DialogInterface.OnClickListener cancel){
        Dialog alertDialog = new AlertDialog.Builder(this).
                setTitle(title).
                setMessage(message).
                //setIcon(R.drawable.).
                setPositiveButton(R.string.info_text_confirm_button, confirm).
                setNegativeButton(R.string.info_text_cancel_button, cancel).
                create();
        alertDialog.show();
    }
    private void ReadHistoryPassword(){
        final ArrayList<HistoryData> list = new ArrayList<HistoryData>();
        MakeHistoryData(list);
        ListView historyView = (ListView)findViewById(R.id.listview_historydata);
        HistoryAdapter adapter = (HistoryAdapter) historyView.getAdapter();
        adapter.UpdateData(list);
        adapter.notifyDataSetChanged();

        displayCurrentPassword(false);
    }
    private void displayCurrentPassword(boolean visible){
        TextView txt = (TextView)findViewById(R.id.main_text_label);
        TextView datetime = (TextView)findViewById(R.id.main_datetime_label);
        ListView history = (ListView)findViewById(R.id.listview_historydata);

        int viewState = View.GONE;
        int hideState = View.GONE;
        if(visible)
        {
            viewState = View.VISIBLE;
            hideState = View.GONE;
        }
        else{
            viewState = View.GONE;
            hideState = View.VISIBLE;
        }
        txt.setVisibility(viewState);
        datetime.setVisibility(viewState);
        history.setVisibility(hideState);
    }

    private Handler mHandle = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            Object data = msg.getData().getSerializable(HistoryAdapter.BUNDLE_KEY_LIDATA);
            switch(msg.what) {
                case HistoryAdapter.CLICK_INDEX_ITEM:
                    //onItemClicked(msg.arg1, data);
                    break;
                case HistoryAdapter.CLICK_INDEX_COUNTRY:
                    //onCountryClicked(data);
                    break;
                case HistoryAdapter.CLICK_INDEX_NAME:
                    //onNameClicked(data);
                    break;
            }
        }

    };

    private void MakeHistoryData(ArrayList<HistoryData> list) {
        for(int i = 0; i < 10; i++) {
            String code = sharedPref.getString(keyprefHistoryPwd+i, kStringBlank);
            String dt = sharedPref.getString(keyprefHistoryTime+i, kStringBlank);
            if(code.isEmpty() || dt.isEmpty()) {
                continue;
            }
            list.add(new HistoryData(code, dt));
        }

    }
    private void AddHistoryData(String code, String dt) {
        SharedPreferences.Editor editor = sharedPref.edit();
        ArrayList<HistoryData> list = new ArrayList<HistoryData>();
        for(int i = 0; i < 10; i++) {
            String codeTemp = sharedPref.getString(keyprefHistoryPwd+i, kStringBlank);
            String dtTemp = sharedPref.getString(keyprefHistoryTime+i, kStringBlank);
            if(code.isEmpty() || dt.isEmpty()) {
                continue;
            }
            list.add(new HistoryData(codeTemp, dtTemp));
        }
        list.add(0, new HistoryData(code, dt));

        for(int i = 0; i < 10; i++) {
            if(list.size() <= i){
                break;
            }
            editor.putString(keyprefHistoryPwd+i, list.get(i).password);
            editor.putString(keyprefHistoryTime+i, list.get(i).datetime);
        }
        editor.commit();
    }

    private void hideAll(){
        TextView txt = (TextView)findViewById(R.id.main_text_label);
        TextView datetime = (TextView)findViewById(R.id.main_datetime_label);
        ListView history = (ListView)findViewById(R.id.listview_historydata);


        txt.setVisibility(View.GONE);
        datetime.setVisibility(View.GONE);
        history.setVisibility(View.GONE);
    }

    @Override
    protected void onPause() {
        super.onPause();
        hideAll();

        getWindow().setFlags(WindowManager.LayoutParams.FLAG_SECURE,
                WindowManager.LayoutParams.FLAG_SECURE);
    }

    private boolean CheckUserPassword(){

        String pwd = sharedPref.getString(keyprefGlobalPwd, kStringBlank);
        String pwdcheck = sharedPref.getString(keyprefGlobalPwdCheck, kStringBlank);

        if(TextUtils.isEmpty(pwd) || pwd.length() <= 0) {
            return false;
        }
        if(!pwd.equals(pwdcheck)){
            return false;
        }
        return true;
    }

    private void GetPreferenceKey(){
        sharedPref = PreferenceManager.getDefaultSharedPreferences(this);

        keyprefCurrentPwd = getString(R.string.preference_key_current_pwd);
        keyprefCurrentTime = getString(R.string.preference_key_current_time);
        keyprefHistoryPwd = getString(R.string.preference_key_history_pwd);
        keyprefHistoryTime = getString(R.string.preference_key_history_time);
        keyprefGlobalPwd = getString(R.string.preference_key_global_pwd);
        keyprefGlobalPwdCheck = getString(R.string.preference_key_global_pwd_check);
        keyprefPasswordLength = getString(R.string.preference_key_pwd_length);
        keyprefEnableFingerprint = getString(R.string.preference_key_enable_fingerprint);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE && resultCode == RESULT_OK) {
            showLoginSuccess();
        }
        //如果改了密码就重新登录
        if(requestCode == SETTING_CODE && resultCode == RESULT_OK) {
            Intent intent = new Intent(this, LoginActivity.class);
            startActivityForResult(intent, REQUEST_CODE);
        }
    }

    private void showLoginSuccess(){
        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        View layout =  navigationView.getHeaderView(0);

        TextView txtLoginState = (TextView)layout.findViewById(R.id.textLoginState);
        TextView txtLoginTime = (TextView)layout.findViewById(R.id.textLoginTime);

        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dt = df.format(new Date());
        if(txtLoginState != null && txtLoginTime != null) {
            txtLoginState.setText(R.string.info_text_login_username);
            txtLoginTime.setText(dt);

            TextView txt = (TextView)findViewById(R.id.main_text_label);
            TextView datetime = (TextView)findViewById(R.id.main_datetime_label);

            txt.setVisibility(View.VISIBLE);
            datetime.setVisibility(View.VISIBLE);
        }
    }
}
